#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<string.h>
#include<limits>
#include<vector>
#include<map>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;


class Dictionary
{
public:
    void read(const std::string&filename);
    void store(const std::string& filename);
private:
    std::map<string,int> _dict;
};

void Dictionary::read(const std:: string & filename)
{
    std::ifstream ifs(filename);
    if(!ifs)
    {
        cout<<"打开文件失败"<<endl;
        return ;
    }
    //利用std::getline(ifs,line);
    //istringstream iss(line)
    //iss>>word
    string line;
    while(std::getline(ifs,line))
    {
        std::istringstream iss(line);
        string word;
        while(iss>>word)
        {
            auto pointer=word.begin();
            for(;pointer<word.end();pointer++)
            {
                if(!isalpha(*pointer))
                {
                    word.erase(pointer);
                }
            }
            cout<<word;
            auto pair=_dict.insert({word,1});
            printf("\r %ld",_dict.size());
            if(pair.second==false)
            {
                _dict[word]++;
            }
        }
    }
    //sort(_dict.begin(),_dict.end());
    //重载<符号一起可以实现对vector<Record>排序
    ifs.close();
    cout<<"read"<<endl;
}

void Dictionary::store(const std::string &filename)
{
    std::ofstream ofs(filename);
    for(auto i:_dict)
    {

        ofs<<"|   "<<std::left<<std::setw(20)<<i.first<<std::setw(10)<<i.second<<std::setw(10)<<"|"<<endl;
        cout<<"|   "<<std::left<<std::setw(20)<<i.first<<std::setw(10)<<i.second<<std::setw(10)<<"|"<<endl;
    }
    ofs.close();
    cout<<"restore"<<endl;
}

int main(void)
{
    string adr;
    cout<<"请输入要查找的文件的绝对地址"<<endl;
    getline(cin,adr);
    Dictionary dic; 
    dic.read(adr);
    cout<<"请输入要保存到的文件名"<<endl;
    adr.clear();
    std::getline(cin,adr);
    dic.store(adr);
}
